
# coding: utf-8

# In[3]:


#使用requests
import requests
import json
import hashlib
import time
import random

def translate(keyword):

    salt = str(int(time.time() * 1000) + random.randint(0, 10))
    # sign是由四部分内容然后计算md5值算出来的
    sign = "fanyideskweb" + keyword + salt + "6x(ZHw]mwzX#u0V7@yfwK"
    m = hashlib.md5()
    m.update(sign.encode('utf-8'))
    #定义POST提交的数据
    data = {
        'i': keyword,
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': salt,
        'sign': m.hexdigest(),
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_REALTIME',
        'typoResult': 'false',
    }
    headers = {
        'Cookie': 'OUTFOX_SEARCH_USER_ID=-1984822116@10.168.8.63; OUTFOX_SEARCH_USER_ID_NCOO=1342120865.1664996; fanyi-ad-id=49843; fanyi-ad-closed=1; JSESSIONID=aaaQbWVqvXc_F8LPUWaxw; ___rl__test__cookies=1536537340332',
         'Referer': 'http://fanyi.youdao.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
    }

    url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
    res = requests.post(url, data=data, headers=headers)
    str_json = res.content.decode("utf-8")
    result = json.loads(str_json)

    for i in range(len(result['smartResult']['entries'])):
        s = result['smartResult']['entries'][i]
        s = s.replace("\n", "")
        print(s)

translate("python")

